package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	v1 "server_go/api/v1"
	"server_go/internal/service"
	"strconv"
)

type ArticleHandler struct {
	*Handler
	articleService service.ArticleService
}

func NewArticleHandler(
	handler *Handler,
	articleService service.ArticleService,
) *ArticleHandler {
	return &ArticleHandler{
		Handler:        handler,
		articleService: articleService,
	}
}

func (h *ArticleHandler) GetArticle(ctx *gin.Context) {

}
func (h *ArticleHandler) CreateArticle(ctx *gin.Context) {
	userType := GetUserTypeFromCtx(ctx)
	fmt.Println(userType)
	if userType != 2 {
		v1.HandleError(ctx, http.StatusUnauthorized, v1.ErrUnauthorized, nil)
		return
	}
	req := new(v1.CreateArticleRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	err := h.articleService.CreateArticle(ctx, *req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}
func (h *ArticleHandler) DeleteArticle(ctx *gin.Context) {
	articleId := ctx.Param("articleId")
	if articleId == "" {
		v1.HandleError(ctx, 400, v1.ErrArticleNotFound, nil)
		return
	}
	ArticleId, err := strconv.Atoi(articleId)
	userType := GetUserTypeFromCtx(ctx)

	userId := GetUserIdFromCtx(ctx)

	err = h.articleService.DeleteArticle(ctx, uint(ArticleId), userId, userType)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)

}
func (h *ArticleHandler) AdminReadArticle(ctx *gin.Context) {

	articles, err := h.articleService.AdminReadArticle(ctx)
	if err != nil {
		v1.HandleError(ctx, 500, v1.ErrNotFound, nil)
		return
	}
	v1.HandleSuccess(ctx, articles)

}
func (h *ArticleHandler) ReadArticlebyUserId(ctx *gin.Context) {
	userId := ctx.Param("userId")
	if userId == "" {
		v1.HandleError(ctx, 400, v1.ErrAdiminNotFound, nil)
		return
	}
	userIdInt, err := strconv.Atoi(userId)
	if err != nil {
		return
	}
	articles, err := h.articleService.ReadArticlebyUserId(ctx, uint(userIdInt))
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, articles)
}
